package com.atguigu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.exception.YyghException;
import com.atguigu.respority.DepartmentRepository;
import com.atguigu.service.DepartmentService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.vo.hosp.DepartmentQueryVo;
import com.atguigu.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void save(Map<String, Object> paramMap) {
        //将数据转换为json字符串
        String string = JSONObject.toJSONString(paramMap);
        //将json字符串转换为 Department类
        Department department = JSONObject.parseObject(string, Department.class);
        //判断 department是否存在
        if (department == null) {
            throw new YyghException(20001, "数据错误");
        }
        //查看科室是否存在
        Department existsDepartment = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        //如果已经存在就修改
        if (existsDepartment != null) {
            //修改
            department.setId(existsDepartment.getId());
            department.setCreateTime(existsDepartment.getCreateTime());
            department.setUpdateTime(existsDepartment.getUpdateTime());
        } else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
        }
        departmentRepository.save(department);
    }

    @Override
    public Page<Department> selectPage(Integer pageNum, Integer limit, DepartmentQueryVo departmentQueryVo) {
        //1、排序（创建时间，降序）
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");

        //2、分页（从0开始）
        Pageable pageable = PageRequest.of(pageNum - 1, limit, sort);
        //3、查询条件
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);

        //4、模糊查询匹配器  字符串包含
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        //5、example对象 把实体对象和匹配器传过来
        Example<Department> example = Example.of(department, matcher);
        //6、调用findAll方法
        Page<Department> pages = departmentRepository.findAll(example, pageable);
        return pages;
    }

    @Override
    public void deleteByHoscodeAndDepcode(String hoscode, String depcode) {
        //先查看科室状态
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (department != null) {
            departmentRepository.deleteById(department.getId());
        }

    }

    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        //根据医院编号查看所有的小科室
       List<Department> list= departmentRepository.findByHoscode(hoscode);
       //根据 bigCode进行分组  bigCode（大科室编号）相同的分到一组
        //key bigCode  valu是大科室编号相同的小科室集合
        Map<String, List<Department>> collect = list.stream().collect(Collectors.groupingBy(Department::getBigcode));
        //对这个map集合进行遍历 将其封装在 DepartmentVo中
        //1创建DepartmentVo对象
        List<DepartmentVo> departmentVoList = new ArrayList<>();
        for(Map.Entry<String,List<Department>> entry: collect.entrySet()){
             //拿到map集合中 key的值
            String key = entry.getKey(); //大科室的编号
            List<Department> value = entry.getValue(); //所有小科室集合
            //每遍历一次 创建一个大科室对象
            DepartmentVo bigDepartment =new DepartmentVo();
            //设置大科室编号
            bigDepartment.setDepcode(key);
            //设置大科室名称
            bigDepartment.setDepname(value.get(0).getBigname());
            //获取大科室下的子科室
            bigDepartment.setChildren(this.transferDepartmentVo(value));
            departmentVoList.add(bigDepartment);
        }
           return  departmentVoList;
    }

    @Override
         //根据科室编号，和医院编号，查询科室名称
    public String getDepName(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        return department.getDepname();
    }

    @Override
    public Department getDepartment(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        return department;
    }

    //遍历小科室集合
    private List<DepartmentVo> transferDepartmentVo(List<Department> value) {
         List<DepartmentVo> departmentVoList = new ArrayList<>();
         value.forEach(department -> {
           DepartmentVo departmentVo =new DepartmentVo();
           departmentVo.setDepcode(department.getDepcode());//小科室编号
           departmentVo.setDepname(department.getDepname());  //小科室名称
           departmentVo.setChildren(null);
           departmentVoList.add(departmentVo);
         });
         return  departmentVoList;
    }


}
